﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
using Engine;
using Gencode;
using Library;

namespace GameTool
{
    public partial class Permission : Form
    {
        private Dictionary<string, string> _userPer = null;
        private Dictionary<string, string> _userPass = null;
        private string _fileName = "user.xml";

        public Permission()
        {
            InitializeComponent();
        }

        private int x = 0;
        private int y = 0;
        private int dx = 2;
        private int dy = 2;
        private int counter = 0;
        private int x1 = 20;
        private int y1 = 20;
        private int dx1 = 12;
        private int dy1 = 12;
        private int counter1 = 0;

        private void Permission_Load(object sender, EventArgs e)
        {
            try
            {
                #region get list user
                ftp_main.download(Common.config.pathXml + "\\Per", _fileName);

                _userPer = new Dictionary<string, string>();
                _userPass = new Dictionary<string, string>();
                XmlDocument _xmlDocument = new XmlDocument();
                _xmlDocument.Load(_fileName);
                XmlNodeList _xmlNodeList = _xmlDocument.GetElementsByTagName("user");
                foreach (XmlNode node in _xmlNodeList)
                {
                    _userPer.Add(node.ChildNodes[0].InnerText, node.ChildNodes[2].InnerText);
                    _userPass.Add(node.ChildNodes[0].InnerText, node.ChildNodes[1].InnerText);
                    AddButton(node.ChildNodes[0].InnerText);
                }
                #endregion

                #region Class

                for (int i = 0; i < Common.ClassList.Count; i++)
                {
                    AddCheckBox(((ClassInfo)Common.ClassList[i]).Name);
                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
        }

        private void AddButton(string userName)
        {
            try
            {
                Button button = new Button();
                button.Text = button.Name = userName;
                button.Size = new Size(75, 23);
                button.FlatStyle = FlatStyle.Flat;
                button.Click += new EventHandler(cmdUser_Click);
                pnlUser.Controls.Add(button);
                int px = x + (counter % 2) * (dx + button.Width);
                int py = y + (counter / 2) * (dy + button.Height);
                button.Location = new Point(px, py);
                counter++;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
        }

        private void Check(string _class)
        {
            foreach (CheckBox c in grpClass.Controls)
            {
                if(c.Name == _class)
                    c.Checked = true;
            }
        }

        private void UnCheckAll()
        {
            foreach (CheckBox c in grpClass.Controls)
            {
                c.Checked = false;
            }
        }

        private void AddCheckBox(string _class)
        {
            CheckBox checkBox = new CheckBox();
            checkBox.Name = _class;
            checkBox.Text = "Lớp " + _class;
            grpClass.Controls.Add(checkBox);
            int px1 = x1 + (counter1 % 2) * (dx1 + checkBox.Width);
            int py1 = y1 + (counter1 / 2) * (dy1 + checkBox.Height);
            checkBox.Location = new Point(px1, py1);
            counter1++;
        }

        private void cmdUser_Click(object sender, EventArgs e)
        {
            try
            {
                string userName = ((Button)sender).Name;
                txtUserName.Text = userName;
                string[] permission = _userPer[userName].Split(' ');
                UnCheckAll();
                foreach (string s in permission)
                {
                    Check(s);
                }
                txtPassword.Text = _userPass[userName];
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
        }

        private void cmdClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cmdOk_Click(object sender, EventArgs e)
        {
            try
            {
                string _userName = txtUserName.Text.Trim();
                string _password = txtPassword.Text.Trim();
                bool _exists = _userPass.ContainsKey(_userName);

                string _permission = string.Empty;
                foreach (CheckBox c in grpClass.Controls)
                {
                    if (c.Checked)
                    {
                        if (_permission.Length > 0)
                        {
                            _permission += " ";
                        }
                        _permission += c.Name;
                    }
                }

                if (_exists)
                {
                    //remove
                    _userPer.Remove(_userName);
                    _userPass.Remove(_userName);
                }

                #region Append
                _userPer.Add(_userName, _permission);
                _userPass.Add(_userName, _password);
                #endregion

                string _mess = Save();
                MessageBox.Show(_mess);

                //show lại
                #region show
                txtUserName.Clear();
                txtPassword.Clear();
                UnCheckAll();
                pnlUser.Controls.Clear();
                counter = 0;
                for (int i = 0; i < _userPer.Count; i++)
                {
                    AddButton(_userPer.ElementAt(i).Key);
                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
        }

        private string Save()
        {
            string _mess = "Successfull!";
            try
            {
                XmlDocument doc = new XmlDocument();
                XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                doc.AppendChild(docNode);
                XmlNode users = doc.CreateElement("users");
                for (int i = 0; i < _userPer.Count; i++)
                {
                    XmlNode user = doc.CreateElement("user");

                    XmlNode username = doc.CreateElement("username");
                    username.AppendChild(doc.CreateTextNode(_userPer.ElementAt(i).Key));
                    user.AppendChild(username);

                    XmlNode password = doc.CreateElement("password");
                    password.AppendChild(doc.CreateTextNode(_userPass.ElementAt(i).Value));
                    user.AppendChild(password);

                    XmlNode permission = doc.CreateElement("permission");
                    permission.AppendChild(doc.CreateTextNode(_userPer.ElementAt(i).Value));
                    user.AppendChild(permission);

                    users.AppendChild(user);
                }

                doc.AppendChild(users);

                doc.Save("user.xml");
                UploadFile.UpFtpFile(Common.config.pathXml, "Per", _fileName, _fileName);
                System.IO.File.Delete(_fileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
            return _mess;
        }

        private void cmDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtUserName.Text.Length < 1)
                    return;
                #region remove
                _userPass.Remove(txtUserName.Text);
                _userPer.Remove(txtUserName.Text);
                #endregion
                #region show
                txtUserName.Clear();
                txtPassword.Clear();
                UnCheckAll();
                pnlUser.Controls.Clear();
                counter = 0;
                for (int i = 0; i < _userPer.Count; i++)
                {
                    AddButton(_userPer.ElementAt(i).Key);
                }
                #endregion
                string _mess = Save();
                MessageBox.Show(_mess);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi!", "Canh bao", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Common.LogException(ex);
                Application.Exit();
            }
        }
    }
}
